package reflect.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class test2 {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("src/reflect/xml/收藏信息.xml");
            //创建Brand节点
            Element brandElement=doc.createElement("Brand");
            brandElement.setAttribute("name","三星");
            //创建Type节点
            Element typeElement=doc.createElement("Type");
            typeElement.setAttribute("name","NoteX");
            //添加父子关系
            brandElement.appendChild(typeElement);
            Element phoneElement=(Element)doc.getElementsByTagName("PhoneInfo").item(0);
            phoneElement.appendChild(brandElement);

            //修改
            NodeList brandList=doc.getElementsByTagName("Brand");
            for(int i=0;i<brandList.getLength();i++){
                Element brand=(Element)brandList.item(i);
                if(brand.getAttribute("name").equals("三星")){
                    brand.setAttribute("name","SAMSUNG");
                }
            }
            //删除
            NodeList list=doc.getElementsByTagName("Brand");
            for(int i=0;i<list.getLength();i++){
                Element elementBrand=(Element)list.item(i);
                if(elementBrand.getAttribute("name").equals("SAMSUNG")){
                    elementBrand.getParentNode().removeChild(elementBrand);
                }
            }

            //保存XML
            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result=new StreamResult(new FileOutputStream("src/reflect/xml/收藏信息.xml"));
            transformer.transform(domSource,result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
